from wordcloud import WordCloud, ImageColorGenerator
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np

with open('test.txt', 'r+', encoding="utf-8") as f:
    dict = {}
    textlist = []
    for word in f.readlines()[0].split("、"):
        if len(word) != 1:
            if '哈' not in word and '+' not in word and word is not '':
                if word not in dict:
                    dict[word] = 1
                    textlist.append(word)
                else:
                    dict[word] += 1
                    textlist.append(word)
L = list(dict.items())
sorted_dict = sorted(L, key=lambda x: x[1], reverse=True)
print(sorted_dict[0:20])
print(len(sorted_dict))
text = " ".join(textlist)
background = Image.open("there.png") #da.png
graph = np.array(background)
word_cloud = WordCloud(font_path="simsun.ttc",
                       background_color="white",
                       # mode='RGBA',
                       width=4200, height=2600,
                       min_font_size=5,
                       # color_func=ImageColorGenerator(graph),
                       mask=graph, scale=1,
                       max_words=4500,
                       max_font_size=80, random_state=29,
                       contour_color='#f13208',
                       contour_width=4
                       )  # 指定词云的形状

word_cloud.generate(text)
plt.subplots(figsize=(12, 8))
plt.imshow(word_cloud)
plt.axis("off")
plt.savefig("therewcloud.jpg")
plt.show()
